package cn.sciento.starter.sms.service;

import cn.sciento.core.exception.CommonException;
import com.baidubce.services.sms.model.SendMessageV2Request;
import com.baidubce.services.sms.model.SendMessageV2Response;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import cn.sciento.core.message.MessageAccessor;
import cn.sciento.starter.sms.configuration.SmsConfigProperties;
import cn.sciento.starter.sms.entity.SmsConfig;
import cn.sciento.starter.sms.entity.SmsMessage;
import cn.sciento.starter.sms.entity.SmsReceiver;
import cn.sciento.starter.sms.exception.SendMessageException;
import cn.sciento.starter.sms.support.BaiduSmsSupporter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class BaiduSmsServiceImpl extends SmsService {
  private static final String OK = "OK";
  
  private final SmsConfigProperties configProperties;
  
  private final ObjectMapper objectMapper;
  
  @Autowired
  public BaiduSmsServiceImpl(SmsConfigProperties configProperties, ObjectMapper objectMapper) {
    this.configProperties = configProperties;
    this.objectMapper = objectMapper;
  }
  
  public String serverType() {
    return "BAIDU";
  }
  
  public void smsSend(List<SmsReceiver> receiverAddressList, SmsConfig smsConfig, SmsMessage message, Map<String, String> args) {
    List<String> telephoneList = new ArrayList<>();
    if (this.configProperties.getSms().isFakeAction() && StringUtils.hasText(this.configProperties.getSms().getFakeAccount())) {
      telephoneList = Collections.singletonList(this.configProperties.getSms().getFakeAccount());
    } else {
      if (this.configProperties.getSms().isFakeAction()) {
        return;
      }
      for (SmsReceiver item : receiverAddressList) {
        String idd = item.getIdd();
        if (!StringUtils.hasLength(idd) || Objects.equals(idd, "+86")) {
          telephoneList.add(item.getPhone());
          continue;
        } 
        throw new CommonException(MessageAccessor.getMessage("hmsg.error.baidu_sms").desc());
      } 
    } 
    SendMessageV2Request request = new SendMessageV2Request();
    request.withInvokeId(smsConfig.getSignName())
      .withTemplateCode(message.getExternalCode())
      .withContentVar(args);
    telephoneList.forEach(phone -> {
          SendMessageV2Response response = BaiduSmsSupporter.sendSms(BaiduSmsSupporter.smsClient(smsConfig), phone, request);
          if (response == null) {
            throw new SendMessageException("baidu sms send failed!");
          }
          if (!response.isSuccess()) {
            throw new SendMessageException(String.format("baidu sms send failed! code: [%s] , message:  [%s]", response.getCode(), response.getMessage()));
          }
        });
  }
}
